package com.study.netty2;

import com.study.constant.Constants;
import com.study.service.ChannelService;
import com.study.revice.ReviceMessageToDealwith;
import com.study.revice.TransformFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;

/**
 * @author mjy
 * @date 2021/12/07
 * @description
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(ServerHandler.class);

    @Autowired
    private ChannelService channelService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        System.out.println("收到客户端【ip:" + clientIp + "】连接");
    }

    /**
     * 1.msg转为实际操作的类
     * 2.保存通道或者刷新通道
     * 3.处理消息
     * 4.写入ctx作为回复
     * 5.写入异常？关闭:成功
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("解析指令：" + msg.toString());
        //此处为准确的处理类
        try {
            ReviceMessageToDealwith dealWithClass = TransformFactory.createReviceMessageToDealWith(String.valueOf(msg));
            String[] split = msg.toString().split(Constants.MESSAGE_SEPARATED);
            //设备身份令牌
            String deviceCard = split[Constants.DEVICE_CARD_INDEX];
            //保存或者刷新身份验证令牌
            channelService.setDeviceOnlineAndRefreshChannle(deviceCard, ctx.channel());
            //解析消息
            dealWithClass.paseMessage(msg.toString());
        } catch (Exception e) {
            logger.error("数据解析异常[{}]", e.getMessage());
        } finally {
            //从netty4开始，对象的生命周期由引用计数器管理
            ReferenceCountUtil.release(msg);
        }


    }

    /**
     * 发生异常
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        channelService.closeChannel(ctx.channel());
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("主动断开连接，通道关闭");
        channelService.closeChannel(ctx.channel());
    }
}
